package ca.inrs.ete.app.shopx.authenticator;

import java.util.List;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import ca.inrs.ete.app.shopx.R;

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
//TODO Split AuthenticationSettings in two PreferenceFragments
public class AuthenticationSettings extends PreferenceActivity {

	/**
	 * Determines whether to always show the simplified settings UI, where
	 * settings are presented in a single list. When false, settings are shown
	 * as a master/detail two-pane view on tablets. When true, a single pane is
	 * shown on tablets.
	 */
	private static final boolean ALWAYS_SIMPLE_PREFS = false;

	public final static String AUTHEN_SETTINGS_BUTTON_CB   = "AuthenticationSettings_button_click_cb";
	public final static String AUTHEN_SETTINGS_REGISTER_CB = "AuthenticationSettings_register_cb";
	public final static String AUTHEN_SETTINGS_ACTION_CB   = "AuthenticationSettings_action_cb";

	public final static String AUTHEN_PREF_URI = "AuthenticationSettings_pref_uri";
	public final static String AUTHEN_PREF_USR = "AuthenticationSettings_pref_usr";
	public final static String AUTHEN_PREF_PWD = "AuthenticationSettings_pref_pwd";
	public final static String AUTHEN_PREF_FRQ = "AuthenticationSettings_pref_sync_frequency";
	public final static String AUTHEN_PREF_LNG = "AuthenticationSettings_pref_lang";
	public final static String AUTHEN_PREF_WFI = "AuthenticationSettings_pref_wifionly";

	public final static int AUTHEN_ACTION_SHOW_PROGRESS = 0;
	public final static int AUTHEN_ACTION_HIDE_PROGRESS = 1;
	public final static int AUTHEN_ACTION_TERMINATE = 2;

	private ResultReceiver mOnClickCB = null;
	private ResultReceiver mRegisterCB= null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mOnClickCB = getIntent().getParcelableExtra(AUTHEN_SETTINGS_BUTTON_CB);
		mRegisterCB= getIntent().getParcelableExtra(AUTHEN_SETTINGS_REGISTER_CB);

		Bundle b = new Bundle();
		b.putParcelable(AuthenticationSettings.AUTHEN_SETTINGS_ACTION_CB , new ResultReceiver(null) {
			@Override
			protected void onReceiveResult(int resultCode, Bundle resultData) {
				switch (resultCode) {
				case AUTHEN_ACTION_SHOW_PROGRESS: AuthenticationSettings.this.showProgress(true); break;
				case AUTHEN_ACTION_HIDE_PROGRESS: AuthenticationSettings.this.showProgress(false); break;
				case AUTHEN_ACTION_TERMINATE:     AuthenticationSettings.this.finish(); break;
				}
			}
		});
		mRegisterCB.send(0, b);

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		requestWindowFeature(Window.FEATURE_PROGRESS);

		super.onCreate(savedInstanceState);
		setupActionBar();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_login, menu);

		/*
		if (mMainMenu != null){
			mMainMenu.findItem(R.id.action_previous).setEnabled(mNbImages > 0);
			mMainMenu.findItem(R.id.action_next).setEnabled(mNbImages > 0);
		}
		 */		
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onStart() {
		super.onStart();
		
		final Intent i = getIntent();
		if (i.getStringExtra(AUTHEN_PREF_URI) != null) {
			SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();

			editor.putString(AUTHEN_PREF_URI, i.getStringExtra(AUTHEN_PREF_URI));
			editor.putString(AUTHEN_PREF_USR, i.getStringExtra(AUTHEN_PREF_USR));
			editor.putString(AUTHEN_PREF_PWD, i.getStringExtra(AUTHEN_PREF_PWD));
			editor.putString(AUTHEN_PREF_FRQ, i.getStringExtra(AUTHEN_PREF_FRQ));
			editor.putString(AUTHEN_PREF_LNG, i.getStringExtra(AUTHEN_PREF_LNG));
			editor.putBoolean(AUTHEN_PREF_WFI,i.getStringExtra(AUTHEN_PREF_WFI) == "1");
			editor.commit();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onStop() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.edit()
			.remove(AUTHEN_PREF_URI)
			.remove(AUTHEN_PREF_USR)
			.remove(AUTHEN_PREF_PWD)
			.remove(AUTHEN_PREF_FRQ)
			.remove(AUTHEN_PREF_FRQ)
			.remove(AUTHEN_PREF_WFI)
			.commit();

		super.onStop();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			// Show the Up button in the action bar.
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		setupSimplePreferencesScreen();
	}

	/**
	 * Shows the simplified settings UI if the device configuration if the
	 * device configuration dictates that a simplified, single-pane UI should be
	 * shown.
	 */
	@SuppressWarnings("deprecation")
	private void setupSimplePreferencesScreen() {
		if (!isSimplePreferences(this)) {
			return;
		}

		// In the simplified UI, fragments are not used at all and we instead
		// use the older PreferenceActivity APIs.

		// Add 'general' preferences.
		addPreferencesFromResource(R.xml.pref_authen_general);

		// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
		// their values. When their values change, their summaries are updated
		// to reflect the new value, per the Android Design guidelines.
		bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_URI));
		bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_USR));
		bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_FRQ));
		bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_LNG));
	}

	/** {@inheritDoc} */
	@Override
	public boolean onIsMultiPane() {
		return isXLargeTablet(this) && !isSimplePreferences(this);
	}

	/**
	 * Helper method to determine if the device has an extra-large screen. For
	 * example, 10" tablets are extra-large.
	 */
	private static boolean isXLargeTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
	}

	/**
	 * Determines whether the simplified settings UI should be shown. This is
	 * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device
	 * doesn't have newer APIs like {@link PreferenceFragment}, or the device
	 * doesn't have an extra-large screen. In these cases, a single-pane
	 * "simplified" settings UI should be shown.
	 */
	private static boolean isSimplePreferences(Context context) {
		return ALWAYS_SIMPLE_PREFS
				|| Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
				|| !isXLargeTablet(context);
	}

	/** {@inheritDoc} */
	@Override
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void onBuildHeaders(List<Header> target) {
		if (!isSimplePreferences(this)) {
			loadHeadersFromResource(R.xml.pref_authen_headers, target);
		}
	}

	/**
	 * A preference value change listener that updates the preference's summary
	 * to reflect its new value.
	 */
	private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
		@Override
		public boolean onPreferenceChange(Preference preference, Object value) {
			String stringValue = value.toString();

			if (preference instanceof ListPreference) {
				// For list preferences, look up the correct display value in
				// the preference's 'entries' list.
				ListPreference listPreference = (ListPreference) preference;
				int index = listPreference.findIndexOfValue(stringValue);

				// Set the summary to reflect the new value.
				preference.setSummary(index >= 0 ? listPreference.getEntries()[index] 
						: null);

			} else {
				// For all other preferences, set the summary to the value's
				// simple string representation.
				preference.setSummary(stringValue);
			}
			return true;
		}
	};

	/**
	 * Binds a preference's summary to its value. More specifically, when the
	 * preference's value is changed, its summary (line of text below the
	 * preference title) is updated to reflect the value. The summary is also
	 * immediately updated upon calling this method. The exact display format is
	 * dependent on the type of preference.
	 * 
	 * @see #sBindPreferenceSummaryToValueListener
	 */
	private static void bindPreferenceSummaryToValue(Preference preference) {
		// Set the listener to watch for value changes.
		preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

		// Trigger the listener immediately with the preference's
		// current value.
		sBindPreferenceSummaryToValueListener.onPreferenceChange(
				preference,
				PreferenceManager.getDefaultSharedPreferences(
						preference.getContext()).getString(preference.getKey(),
								""));
	}

	/**
	 * This fragment shows general preferences only. It is used when the
	 * activity is showing a two-pane settings UI.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static class GeneralPreferenceFragment extends PreferenceFragment {
		public GeneralPreferenceFragment() {
		}
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			addPreferencesFromResource(R.xml.pref_authen_general);

			// Bind the summaries of EditText/List/Dialog preferences
			// to their values. When their values change, their summaries are
			// updated to reflect the new value, per the Android Design
			// guidelines.
			bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_URI));
			bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_USR));
			bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_FRQ));
			bindPreferenceSummaryToValue(findPreference(AUTHEN_PREF_LNG));
		}
	}

	/**
	 * Transfer preferences to a bundle a ship to the callback
	 */
	public void onButtonClick(MenuItem item) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Bundle b = new Bundle();
		b.putString(AUTHEN_PREF_URI, prefs.getString(AUTHEN_PREF_URI, ""));
		b.putString(AUTHEN_PREF_USR, prefs.getString(AUTHEN_PREF_USR, ""));
		b.putString(AUTHEN_PREF_PWD, prefs.getString(AUTHEN_PREF_PWD, ""));
		b.putString(AUTHEN_PREF_FRQ, prefs.getString(AUTHEN_PREF_FRQ, ""));
		b.putString(AUTHEN_PREF_LNG, prefs.getString(AUTHEN_PREF_FRQ, ""));
		b.putString(AUTHEN_PREF_WFI, prefs.getBoolean(AUTHEN_PREF_WFI, true) ? "1" : "0");

		mOnClickCB.send(0, b);
	}

	public void showProgress(boolean b) {
		setProgressBarVisibility(b);
	}
}
